package com.miya.demo.support.netty.server;

import com.miya.demo.support.netty.config.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 服务端启动
 *
 * @author CaiXiaowei
 * @date 2023/1/17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ServerBoot {

    @NonNull
    private ServerBootstrap serverBootstrap;
    @NonNull
    private NioEventLoopGroup boosGroup;
    @NonNull
    private NioEventLoopGroup workerGroup;
    @NonNull
    private NettyProperties nettyProperties;

    @PostConstruct
    public void start() throws InterruptedException {
        // 绑定端口启动
        serverBootstrap.bind(nettyProperties.getPort()).sync();
        log.info("启动netty多端口服务, 主端口:{}", nettyProperties.getPort());
//        serverBootstrap.bind(nettyProperties.getPortSalve()).sync();
//        log.info("启动netty多端口服务, 主端口:{}, 从端口:{}", nettyProperties.getPort(), nettyProperties.getPortSalve());
    }

    @PreDestroy
    public void close() {
        log.info("关闭线程池.");
        boosGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
